package com.kingyun.gpsinspection.purificationservice.services.tdm.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.common.enums.WorkOrderFinishTypeEnum;
import com.kingyun.gpsinspection.purificationservice.common.enums.WorkOrderStatusEnum;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.AbnormalWorkOrderMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.WorkOrderApplyMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.WorkOrderEmployeeMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmWorkOrderMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.AbnormalWorkOrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jiangjx on 2017/1/20.
 * 非正常工单处置service实现
 */
public class AbnormalWorkOrderServiceImpl implements AbnormalWorkOrderService {
    @Autowired
    private AbnormalWorkOrderMapper abnormalWorkOrderMapper;

    @Autowired
    private TdmWorkOrderMapper tdmWorkOrderMapper;

    @Autowired
    private WorkOrderApplyMapper workOrderApplyMapper;

    @Autowired
    private WorkOrderEmployeeMapper workOrderEmployeeMapper;

    /**
     * 查询异常工单table数据
     *
     * @param abnormalWorkOrderVo 查询条件
     * @return
     */
    @Override
    public JSONObject queryAbnormalWorkOrderList(AbnormalWorkOrderVo abnormalWorkOrderVo) throws Exception {
        /*装载查询条件*/
        abnormalWorkOrderVo.setLimit(null == abnormalWorkOrderVo.getLimit() ? 10 : abnormalWorkOrderVo.getLimit());
        abnormalWorkOrderVo.setOffset(null == abnormalWorkOrderVo.getOffset() ? 0 : abnormalWorkOrderVo.getOffset());
        JSONObject jsonObject = new JSONObject();
        /* 进行分页查询分离 */
        jsonObject.put("total", abnormalWorkOrderMapper.queryCount(abnormalWorkOrderVo));//查询总条数
        List<AbnormalWorkOrder> baseRows = abnormalWorkOrderMapper.queryTableList(abnormalWorkOrderVo);//查询分页内容
        /*返回结果*/
        jsonObject.put("rows", JSON.toJSON(baseRows));
        return jsonObject;
    }

    /**
     * 修改工单状态（审批）
     *
     * @param employeeVo
     * @param workOrderId    工单id
     * @param approveState   审批意见：0同意，1驳回
     * @param approveOpinion 审批备注
     * @return
     */
    @Override
    public boolean updateWorkOrder(EmployeeVo employeeVo, String workOrderId, String approveState, String approveOpinion) throws Exception {
        Boolean returnFlag = false;
        WorkOrder workOrder = tdmWorkOrderMapper.selectByPrimaryKey(workOrderId);//查询工单信息
        //判断工单是否存在
        if (null != workOrder) {
            /*封装需要修改的数据*/
            workOrder = new WorkOrder();
            workOrder.setWorkOrderId(workOrderId);//set工单id
            workOrder.setModifyTime(new Date());//set修改日期
            workOrder.setModifyUserId(employeeVo.getEmployeeId());//set修改人id
            workOrder.setCanFinish(approveState.equals("0") ? WorkOrderFinishTypeEnum.FINISH_TYPE_ENUM_3.code() : WorkOrderFinishTypeEnum.FINISH_TYPE_ENUM_1.code()); //修改工单状态
            int i = tdmWorkOrderMapper.updateByPrimaryKeySelective(workOrder);//执行修改操作
            if (i > 0) {
                returnFlag = true;
            }
            /*保存审批信息*/
            WorkOrderApply workOrderApply = new WorkOrderApply();
            workOrderApply.setWorkOrderId(workOrderId);//set工单id
            workOrderApply.setApproveTime(new Date());//set审批日期
            workOrderApply.setIsDealed(new Short("1"));//set状态（是否完成，0未完成，1已完成）
            workOrderApply.setApproveUserId(employeeVo.getEmployeeId());//set审批人
            workOrderApply.setApproveOpinion(approveOpinion);//set审批意见
            workOrderApplyMapper.updateByWorkOrderIdSelective(workOrderApply);//保存审批信息
        }
        return returnFlag;
    }

    /**
     * 关闭工单
     *
     * @param employeeVo
     * @param workOrderId 工单id
     * @return
     */
    @Override
    public boolean closeWorkOrder(EmployeeVo employeeVo, String workOrderId) {
        Boolean returnFlag = false;//返回标志位
        WorkOrderVo workOrderVo = new WorkOrderVo();
        workOrderVo.setWorkOrderId(workOrderId);
        workOrderVo.setModifyTime(new Date());//set修改日期
        workOrderVo.setModifyUserId(employeeVo.getEmployeeId());//set修改人id
        workOrderVo.setStatus(WorkOrderStatusEnum.WORK_ORDER_STATUS_ENUM_7.code());//set工单状态：关闭工单
        int tempFlag = tdmWorkOrderMapper.updateByPrimaryKeySelective(workOrderVo);//执行修改操作
        if (tempFlag > 0) {
            returnFlag = true;
        }
        return returnFlag;
    }


    /**
     * 修改工单信息
     *
     * @param employeeVo
     * @param workOrderVo 工单对象
     * @return
     */
    @Override
    public Boolean updateWorkOrder(EmployeeVo employeeVo, WorkOrderVo workOrderVo) {
        Boolean returnFlag = false;//返回标志位
        workOrderVo.setModifyTime(new Date());//set修改日期
        workOrderVo.setModifyUserId(employeeVo.getEmployeeId());//set修改人id
        workOrderVo.setCanFinish(WorkOrderFinishTypeEnum.FINISH_TYPE_ENUM_1.code());
        int tempFlag = tdmWorkOrderMapper.updateByPrimaryKeySelective(workOrderVo);//修改工单基本信息
        //修改工单执行人信息
        updateUserId(workOrderVo);
        if (tempFlag > 0) {
            returnFlag = true;
        }
        return returnFlag;
    }

    /**
     * 修改工单执行人信息
     *
     * @param workOrderVo 工单信息
     */
    private void updateUserId(WorkOrderVo workOrderVo) {
        //新增关系
        String[] userIds = workOrderVo.getUserId().split(",");
        if (userIds != null && userIds.length > 0) {
            List<WorkOrderEmployee> list = new ArrayList<>();
            for (String id : userIds) {
                if (StringUtils.isNotBlank(id)) {
                    /*封装数据*/
                    WorkOrderEmployee workOrderEmployee = new WorkOrderEmployee();
                    workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());//set主键
                    workOrderEmployee.setWorkOrderId(workOrderVo.getWorkOrderId());//set工单id
                    workOrderEmployee.setEmployeeId(id);//set人员ID
                    list.add(workOrderEmployee);//添加对象
                }
            }
            if (null != list && list.size() != 0) {
                workOrderEmployeeMapper.deleteByWorkOrderId(workOrderVo.getWorkOrderId());//删除关系
                workOrderEmployeeMapper.insertList(list);//批量插入关联数据
            }
        }
    }

    /**
     * 获取工单信息
     *
     * @param workOrderId 工单id
     */
    @Override
    public WorkOrderVo getWorkOrderInfo(String workOrderId) {
        return tdmWorkOrderMapper.queryByPrimaryKey(workOrderId);
    }

    /**
     * 记载审批信息
     *
     * @param workOrderApply
     * @return
     */
    @Override
    public JSONObject loadApproveInfo(WorkOrderApply workOrderApply) {
       /*装载查询条件*/
        JSONObject jsonObject = new JSONObject();
        /* 查询列表 */
        jsonObject.put("total", workOrderApplyMapper.queryCount(workOrderApply));//查询总条数
        List<WorkOrderApply> baseRows = workOrderApplyMapper.queryTableList(workOrderApply);//查询分页内容
        /*返回结果*/
        jsonObject.put("rows", JSON.toJSON(baseRows));
        return jsonObject;
    }
}
